<template>
	<view class="page-detail content-box">
		<view class="tips" v-if="actionStep===CHOICE">
			从下面句子中选出不认识的词
		</view>
		<view class="detail" :class="visibleNextBtn?'has-btn':''">
			<sentence v-if="visibleActionSentence" v-model:value="choiceWords" :action-step="actionStep"></sentence>
			<single-selection v-if="visibleSingleSelection" v-bind="testAttrs" @next="getNextflag" />
			<spell-word v-if="visibleSpellWord" v-bind="spellAttrs" :timer-bar-sty="timerBarSty" @next="getNextflag" />
		</view>
		<view class="h-20rpx" v-if="actionStep!==CHOICE"></view>
		<view class="bottom-btn-box" v-if="visibleNextBtn">
			<u-button @click="handelNext" class="next-btn w-full" type="warning" :plain="true">
				<view class="next-text">继续</view>
			</u-button>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed, onMounted, nextTick, provide } from 'vue';
	import { useStudyStore, IWord, IUseTemplate, TestTemplates, TestTemplate } from '@/store/study';
	import { deepClone, isUnde, ktlapi, OT } from '@/utils';
	import { useTest } from '@/common/hooks';
	import Sentence from '@/pages-study/components/sentence/sentence.vue';
	import SingleSelection from '@/pages-study/components/single-selection/single-selection.vue';
	import SpellWord from '@/pages-study/components/spell-word/spell-word.vue';

	/** 步骤：筛词环节 */
	defineOptions({ name: 'step-sentence', inheritAttrs: false, options: { virtualHost: true } });
	// 声明组件基本要素
	const emit = defineEmits(['module-event']);
	// hooks 初始化
	const testUtil = useTest();
	const studyStore = useStudyStore();
	const { CHOICE, CHOICE_COMPLETE, TEST_COMPLETE } = studyStore.choiceActionStep;
	withDefaults(defineProps<{ timerBarSty: any }>(), { timerBarSty:'' })
	
	// 二次验证
	provide('doubleVisible', true);
	
	// 声明用户变量
	const { HYY, YYH, TX, SPELL, SPELL_SIMPLE } = TestTemplates;
	// 选中的不认识的词
	const choiceWords = ref<IWord[]>([]);
	// 筛词进度
	const actionStep = ref<string>(CHOICE);
	const checked = ref(false);
	const current = ref<IWord>(null);
	const stepData = ref<IWord[]>([]);
	const type = ref<any>(null);
	const testAttrs = ref<any>({});
	const spellAttrs = ref<any>({});
	// 单选组件显示状态
	const visibleSingleSelection = ref(false);
	// 单词拼写显示状态
	const visibleSpellWord = ref(false);

	const errorPct = ref<number>(0);
	// 惩罚机制
	const CFCount = 0;
	// 惩罚最大限制
	const CFMaxCount = 1;
	const remeberedWords = ref<IWord[]>([]);

	// 当前测试类型
	const currentType = ref<any>({});
	const SingleTemplates = [YYH, HYY];
	const SpellTemplates = [SPELL, SPELL_SIMPLE];

	// 声明计算属性
	const visibleActionSentence = computed(() => [CHOICE, TEST_COMPLETE].includes(actionStep.value));
	const visibleNextBtn = computed(() => [CHOICE, TEST_COMPLETE].includes(actionStep.value));

	// 测试工具执行方案
	const handelNextTester = () => {
		// 开启了测试工具
		if (studyStore.tester.isTestMode) {
			if (studyStore.tester.filterWordTest) {
				initTestTemplate();
				actionStep.value = CHOICE_COMPLETE;
			} else {
				visibleSingleSelection.value = false;
				visibleSpellWord.value = false;
				actionStep.value = TEST_COMPLETE;
				// 将studyStore.wordGroup中没有的词，放进去
				choiceWords.value.forEach(item => {
					if (!studyStore.wordGroup.some(wg => wg.WordId === item.WordId)) {
						studyStore.wordGroup.push({
							...item,
							SentenceId: studyStore.wordGroup[0].SentenceId,
							SentenceSnapshot: studyStore.wordGroup[0].SentenceSnapshot,
							LostLv: isUnde(item.LostLv) ? 18 : item.LostLv
						})
					}
				})
			}
			return true;
		}
		return false;
	}
	
	// 声明函数
	const handelNext = () => {
		console.log('TEST_COMPLETE choiceWords.value', choiceWords.value);
		if (actionStep.value === CHOICE) {
			// console.log('choiceWords', choiceWords.value);
			getRemeberedWords();
			// console.log('remeberedWords.value', remeberedWords.value);
			if (remeberedWords.value.length > 0) {
				// 开启了测试工具
				if (handelNextTester()) {
					return;
				}
				
				initTestTemplate();
				actionStep.value = CHOICE_COMPLETE;
			} else {
				visibleSingleSelection.value = false;
				visibleSpellWord.value = false;
				actionStep.value = TEST_COMPLETE;
				// 将studyStore.wordGroup中没有的词，放进去
				choiceWords.value.forEach(item => {
					if (!studyStore.wordGroup.some(wg => wg.WordId === item.WordId)) {
						studyStore.wordGroup.push({
							...item,
							SentenceId: studyStore.wordGroup[0].SentenceId,
							SentenceSnapshot: studyStore.wordGroup[0].SentenceSnapshot,
							LostLv: isUnde(item.LostLv) ? 18 : item.LostLv
						})
					}
				})
				return;
			}
		}

		if (actionStep.value === TEST_COMPLETE) {
			// if (studyStore.tester.isTestMode) {
				
			// }
			addRemeberProcess(() => {
				emit('module-event', { action: 'next', payload: { isAllRight: choiceWords.value.length === 0 } });
			});
		}
	}

	// 获取本组词汇中学员记住的词汇
	function getRemeberedWords() {
		const remeberedWordList = studyStore.wordGroup.filter(wordInfo => {
			return !choiceWords.value.some(unChoiceWord => unChoiceWord.Word.toLowerCase() === wordInfo.Word.toLowerCase())
		})
		remeberedWords.value = deepClone(remeberedWordList);
		// console.log('remeberedWords.value', remeberedWords.value)
	}

	function initTestTemplate() {
		var useTemplates : TestTemplate[] = [HYY, YYH];
		const cloneWords : IWord[] = deepClone(remeberedWords.value);
		for (var i = 0; i < cloneWords.length; i++) {
			let tempUseTemplates = [...useTemplates]
			if (cloneWords[i].NeedWrite) {
				tempUseTemplates = [...tempUseTemplates];
				if (cloneWords[i].Word.length > 6) {
					tempUseTemplates.push(SPELL_SIMPLE)
				} else {
					tempUseTemplates.push(SPELL)
				}
			}
			cloneWords[i].UseTemplates = testUtil.initUseTemplateConfig(tempUseTemplates, { TotalCount: 1, ErrorCount: 0 })
		}

		// 将studyStore.wordGroup中没有的词，放进去
		choiceWords.value.forEach(item => {
			if (!studyStore.wordGroup.some(wg => wg.WordId === item.WordId)) {
				studyStore.wordGroup.push({
					...item,
					SentenceId: studyStore.wordGroup[0].SentenceId,
					SentenceSnapshot: studyStore.wordGroup[0].SentenceSnapshot,
					LostLv: isUnde(item.LostLv) ? 18 : item.LostLv
				})
			}
		})

		testUtil.fillTestData(cloneWords, [...studyStore.wordGroup, ...studyStore.shuffleWords]);
		stepData.value = cloneWords;

		handelTestNext();
	}

	// 保存进度
	function addRemeberProcess(callback?: any) {
		studyStore.wordGroup.forEach(item => {
			const findCW = choiceWords.value.find(cw => cw.WordId === item.WordId);
			if (findCW) {
				item.NeedRemeber = true;
				item.LostLv = isUnde(findCW.LostLv) ? 18 : findCW.LostLv;
			} else {
				item.NeedRemeber = false;
				item.LostLv = 0;
			}
		})
		
		console.log('Cus_AddRemeberProcess 参数', studyStore.wordGroup.map(wordInfo => {
				return {
					WordId: wordInfo.WordId,
					LessonId: studyStore.LessonUUID,
					SentenceId: wordInfo.SentenceId,
					SentenceSnapshot: JSON.stringify(wordInfo.SentenceSnapshot),
					LostLv: wordInfo.LostLv,
					IsFinished: wordInfo.NeedRemeber ? 0 : 1
				}
			}))
	
		ktlapi({
			apiurl: OT.CommandAddSet,
			action: 'Cus_AddRemeberProcess',
			data: studyStore.wordGroup.map(wordInfo => {
				return {
					WordId: wordInfo.WordId,
					LessonId: studyStore.LessonUUID,
					SentenceId: wordInfo.SentenceId,
					SentenceSnapshot: JSON.stringify(wordInfo.SentenceSnapshot),
					LostLv: wordInfo.LostLv,
					IsFinished: wordInfo.NeedRemeber ? 0 : 1
				}
			})
		}).then((_res : any) => {
			if (choiceWords.value.length > 0) {
				actionStep.value = TEST_COMPLETE;
				visibleSingleSelection.value = false;
				visibleSpellWord.value = false;
				if (callback) {
					callback()
				}
			} else {
				// console.log('handelTestNext choiceWords.value', choiceWords.value);
				emit('module-event', { action: 'next', payload: { isAllRight: true } });
			}
		})
	}
	/** 测试下一题 */
	function handelTestNext() {
		const result = testUtil.findCurrent(stepData.value);
		if (result.found) {
			// testAttrs.value = {};
			const { type } = result.attrs;

			// 前一测试类型属于[单选模板]
			if (testUtil.hasTemplate(SingleTemplates, currentType.value)) {
				// 新的测试类型不属于[单选模板]，隐藏[单选模板]
				if (!testUtil.hasTemplate(SingleTemplates, type)) {
					visibleSingleSelection.value = false;
				}
			}
			// 前一测试类型属于[拼写模板]
			else if (testUtil.hasTemplate(SpellTemplates, currentType.value)) {
				// 新的测试类型不属于[拼写模板]，隐藏[拼写模板]
				if (!testUtil.hasTemplate(SpellTemplates, type)) {
					visibleSpellWord.value = false;
				}
			}

			// 新的测试类型属于[单选模板], 显示[单选模板]
			if (testUtil.hasTemplate(SingleTemplates, type)) {
				visibleSingleSelection.value = true;
			}
			// 新的测试类型属于[拼写模板], 显示[拼写模板]
			if (testUtil.hasTemplate(SpellTemplates, type)) {
				visibleSpellWord.value = true;
			}

			nextTick().then(() => {
				currentType.value = type;
				testAttrs.value = {
					...result.attrs,
					effect: true,
					pause: true,
					jump: false,
					errLearn: false
				};
				spellAttrs.value = {
					...result.attrs,
					effect: true,
					pause: true,
					jump: true,
					errLearn: false
				}
			})

			console.log('result.found', result.found)
			// current.value = result.attrs.current;
			// type.value = result.attrs.type;
			return;
		}
		
		stepData.value.forEach(item => {
			const findCW = choiceWords.value.find(cw => cw.WordId === item.WordId);
			if (!findCW) return;
			const isRight = item.UseTemplates.every(utl => utl.ErrorCount === 0);
			// 已经掌握了这个词
			if (isRight) {
				findCW.LostLv = 0;
			} else {
				findCW.NeedRemeber = true;
				let sumAllWeight = 0;
				let sumErrorWeight = 0;
				item.UseTemplates.forEach(utl => {
					const weight = utl.template.weight;
					sumAllWeight += weight;
					if (utl.ErrorCount > 0) {
						sumErrorWeight += weight;
					}
				});  
				findCW.LostLv = 18 - (sumAllWeight - sumErrorWeight);
			}
		})
		
		visibleSingleSelection.value = false;
		visibleSpellWord.value = false;
		actionStep.value = TEST_COMPLETE;
	}

	function getNextflag(_item : IWord, isright : boolean, isJump : boolean) {
		const { type, current } = testAttrs.value;
		if (!isright) {
			// 二次校验，发现做错了，加入生词列表
			if (!choiceWords.value.some(cw => cw.Word.toLowerCase() === current.Word.toLowerCase())) {
				choiceWords.value.push({ ...current });
			}
		}

		stepData.value.forEach(item => {
			if (current.WordId === item.WordId) {
				for (let i = 0; i < item.UseTemplates.length; i++) {
					if (testUtil.getTemplateType(item.UseTemplates[i]) == testUtil.getTemplateType(type)) {
						item.UseTemplates[i]["TotalCount"] -= 1;
						if (!isright) {
							item.UseTemplates[i]["ErrorCount"] += 1;
							item.UseTemplates[i]["TotalCount"] += CFCount;

							if (item.UseTemplates[i]["TotalCount"] > CFMaxCount) {
								item.UseTemplates[i]["TotalCount"] = CFMaxCount
							}
						}
						// break;
					}
					else if (!isright) {
						item.UseTemplates[i]["TotalCount"] = 0;
					}
				}
			}
		})

		handelTestNext()
	}

	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	// 声明函数
	function playMp3(mp3 : string) {


		if (mp3.includes('http')) {
			innerAudioContext.src = mp3;
		} else {
			innerAudioContext.src = 'https://nx5.abc5g.com/' + mp3;
		}
		innerAudioContext.play();
		innerAudioContext.onPlay(() => {

		});
		innerAudioContext.onError((res) => {
			console.log(res.errMsg);
			console.log(res.errCode);
		});
	}

	onMounted(() => {

	})
</script>

<style lang="scss" scoped>
	.content-box {
		--font-color: #332c2b;
		margin: 0 30rpx;
	}

	.tips {
		text-align: center;
		font-size: var(--text-14);
		color: #777;
		margin: 10px;
		flex-shrink: 0;
	}

	.next-btn {
		/* #ifdef H5 */
		height: 45px !important;
		/* #endif */
	}

	.next-text {
		font-size: var(--text-18);
		font-weight: bold;
		display: flex;
	}
	
	.detail{
		/* #ifdef H5 */
		height: calc(100vh - 155px) !important;
		/* #endif */
		
		/* #ifdef MP */
		height: calc(100vh - 387rpx) !important;
		/* #endif */
	}
	.detail.has-btn{
		/* #ifdef H5 */
		height: calc(100vh - 230px) !important;
		/* #endif */
		
		/* #ifdef MP */
		height: calc(100vh - 500rpx) !important;
		/* #endif */
	}

	/* 针对 1280px 分辨率 */
	@media(min-width:1200px) {
		.content-box {
			width: 2400rpx;
			margin: 0 auto !important;
		}

		.process {
			min-width: 238rpx;
		}

		.detail {}
	}
</style>